<template>
  <div class="div_box">
    <!-- 面包屑 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item to="/Home">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 表格 -->
    <div class="div">
      <el-button type="primary" @click="dialogVisible = true"
      >添加角色
      </el-button>
      <el-table :data="list" style="width: 100%" border>
        <!--         折叠面板 -->
        <el-table-column type="expand" prop="data" label="" width="40">
          <template slot-scope="scope">
            <!--   一级-->
            <div v-if="scope.row.children.length > 0">
              <el-row :class="['bt_border', idx1 === 0 ? 'tp_border' : '']"
                      v-for="(item1, idx1) in scope.row.children"
                      :key="item1.id"
              >
                <el-col :span="6">
                  <el-tag
                      @close="delrole(scope.row, item1.id)"
                      closable
                  >{{ item1.authName }}
                  </el-tag>
                </el-col>
                <el-col :span="18">
                  <!-- 二级权限 -->
                  <el-row v-for="item2 in item1.children" :key="item2.id">
                    <el-col :span="6">
                      <el-tag
                          @close="delrole(scope.row, item2.id)"
                          closable
                          type="success"
                      >{{ item2.authName }}
                      </el-tag
                      >
                      <i class="el-icon-caret-right"></i>
                    </el-col>
                    <el-col :span="18">
                      <el-tag
                          closable
                          type="warning"
                          v-for="item3 in item2.children"
                          :key="item3.id"
                          @close="delrole(scope.row, item3.id)"
                      >
                        {{ item3.authName }}
                      </el-tag>
                    </el-col>
                  </el-row>
                </el-col>
              </el-row>
            </div>
            <div v-else>该角色暂无权限</div>
          </template>
        </el-table-column>
        <el-table-column prop="id" label="#" width="40"></el-table-column>
        <el-table-column prop="roleName" label="角色名称" width="280">
        </el-table-column>
        <el-table-column prop="roleDesc" label="角色描述" width="380">
        </el-table-column>
        <el-table-column prop="address" label="操作">
          <template slot-scope="scope">
            <div>
              <el-button
                  size="mini"
                  type="primary"
                  icon="el-icon-edit"
                  @click.prevent="bianjianniu = true"
                  @click="bianjier(scope.row)"

              >编辑
              </el-button
              >
              <el-button
                  size="mini"
                  type="danger"
                  icon="el-icon-delete"
                  @click="shanchu(scope.row)"
              >删除
              </el-button
              >
              <el-button size="mini" type="warning" icon="el-icon-setting"
                         @click="fenpei(scope.row)"
              >分配权限
              </el-button
              >
            </div>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <!-- 添加弹框 -->
    <el-dialog
        title="添加角色"
        :visible.sync="dialogVisible"
        width="30%"
        :before-close="handleClose"
    >
      <el-form ref="form" :model="from" :rules="froms" label-width="100px">
        <el-form-item label="角色名称：" prop="roleName">
          <el-input v-model="from.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述：" prop="roleDesc">
          <el-input v-model="from.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <el-button @click="dialogVisible = false">取 消</el-button>
      <el-button type="primary" @click="add">确 定</el-button>
    </el-dialog>
    <!-- 编辑弹框 -->
    <el-dialog title="提示" :visible.sync="bianjianniu" width="30%">
      <el-form ref="form" :model="bianjiList" :rules="bianjiLists" label-width="80px">
        <template>
          <div>
            <el-form-item label="角色名称" prop="roleName">
              <el-input v-model="bianjiList.roleName"></el-input>
            </el-form-item>
            <el-form-item label="角色描述" prop="roleDesc">
              <el-input v-model="bianjiList.roleDesc"></el-input>
            </el-form-item>
          </div>
        </template>
      </el-form>

      <el-button @click="bianjianniu = false">取 消</el-button>
      <el-button type="primary" @click="xiugai">确 定</el-button>
    </el-dialog>
    <!-- 分配权限-->
    <el-dialog title="分配权限" :visible.sync="Trees" @close="resetTree">
      <el-tree
          :data="data"
          show-checkbox
          default-expand-all
          node-key="id"
          ref="path"
          :default-checked-keys="checkedKeysArr"
          :props="defaultProps"
      >
      </el-tree>
      <div slot="footer" class="dialog-footer">
        <el-button @click="Trees = false">取 消</el-button>
        <el-button type="primary" @click="setRightsToRole">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  liaobiaoroles,
  liaobiaoxinxi,
  liebiaoshanchu,
  liebiaobianji, delroles,getTree,setRightsToRoleAPI
} from "@/utils/api";

export default {
  name: "",
  data() {
    return {
      checkedKeysArr:[],
      //编辑
      bianjiId: "",
      list: [],
      data: [],
      defaultProps: {
        children: 'children',
        label: 'authName'
      },

      //弹出表单
      dialogVisible: false,
      bianjianniu: false,
      Trees: false,
      from: {
        roleName: "",
        roleDesc: "",
      },
      froms: {
        roleName: [{required: true, message: '请填写用户名', trigger: 'blur'},
          {min: 4, max: 16, message: '请输入长度在4到16之间的字符个数', trigger: 'blur'}],
        roleDesc: [{required: true, message: '请填写用户名', trigger: 'blur'},
          {min: 2, max: 16, message: '请输入长度在2到16之间的字符个数', trigger: 'blur'}],
      }, id: '',
      bianjiList: {
        roleName: "",
        roleDesc: "",
      },
      bianjiLists: {
        roleName: [{required: true, message: '请填写用户名', trigger: 'blur'},
          {min: 4, max: 16, message: '请输入长度在4到16之间的字符个数', trigger: 'blur'}],
        roleDesc: [{required: true, message: '请填写用户名', trigger: 'blur'},
          {min: 2, max: 16, message: '请输入长度在2到16之间的字符个数', trigger: 'blur'}],
      },
      //数据流
      liaobiaoroles() {
        liaobiaoroles().then((res) => {
          this.list = res;
        });
      },

    };
  },
  created() {
    this.liaobiaoroles();
  },
  mounted() {
  },
  methods: {
    handleClose(done) {
      this.$confirm("确认关闭？")
          .then((_) => {
            done();
          })
          .catch((_) => {
          });
    },
    // 添加事件
    add() {
      liaobiaoxinxi(this.from).then((res) => {
        console.log(res);
        this.liaobiaoroles();
        this.dialogVisible = false
      });
    },
    //删除
    shanchu(i) {
      this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        let id = i.id;
        console.log(id);
        liebiaoshanchu(id).then((res) => {
          this.liaobiaoroles();
        });
      })
    },
    //编辑
    bianjier(i) {
      console.log(i);
      this.id = i.id
      this.bianjiList.roleName = i.roleName
      this.bianjiList.roleDesc = i.roleDesc
    },
    xiugai() {
      // console.log(1);
      liebiaobianji(this.id, this.bianjiList).then(res => {
        console.log(res)
        this.liaobiaoroles();
      })
      this.bianjianniu = false
    },
    //分配
    async setRightsToRole() {
      //全选
      let nodeArr=[
        //全选中
        ...this.$refs.path.getCheckedKeys(),
        //半选中
        ...this.$refs.path.getHalfCheckedKeys()
      ]
      let nodeStr=nodeArr.join(',')
      const res= await setRightsToRoleAPI(this.currentRoleId,{rids:nodeStr})
      console.log('分配成功结果：',res)
      this.liaobiaoroles();
      this.Trees=false;

    },
    async fenpei(i){
      this.currentRoleId=i.id;
      console.log('当前角色id：',this.currentRoleId)
      //调树形接口
      const res= await getTree()
      console.log('树形权限列表：',res)
      //调用获取当前角色所有权限id的方法
      this.getCheckedRightsIds(i,this.checkedKeysArr)
      this.data=res;
      //显示对话框
      this.Trees = true;
    },
    //递归获取最后一级权限所有id组成一个数组，例如：[22,4,66,7,88,9,3,3]
    getCheckedRightsIds(node,arr) {
      //当前node没有children,意味着node没有子级，则将当前node的id保存到数组中
      if(!node.children) {
        return arr.push(node.id)
      }

      //如果node含有children，则用递用调用getCheckedRightsIds函数
      node.children.forEach(subnode=>this.getCheckedRightsIds(subnode,arr))
    },
    //删除角色指定权限方法
    async delrole(role, rightId) {
      console.log(role)
      //调删除角色指定权限接口
      const res = await delroles(role.id, rightId);
      console.log(res)
      role.children = res;
    },
    resetTree() {
      this.checkedKeysArr = [];
    }

  },
};
</script>

<style lang='scss' scoped>
.el-button {
  margin-top: 20px;
  margin-left: 15px;
}

.el-table {
  margin-top: 10px;
}

.div {
  background: #ffff;
  margin-top: 20px;
}

.div_box {
  overflow-y: auto;
  height: 90vh;
}

.bt_border {
  border-bottom: 1px solid #eee;
}

.tp_border {
  border-top: 1px solid #eee;
}
</style>